package com.och.mrcp.handler;

import com.och.mrcp.core.sip.model.SipMessage;
import com.och.mrcp.core.sip.model.SipRequest;
import com.och.mrcp.core.sip.model.SipResponse;
import com.och.mrcp.core.sip.parser.SipMessageParser;
import com.och.mrcp.core.sip.transaction.SipTransaction;
import com.och.mrcp.core.sip.transaction.SipTransactionManager;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.buffer.Unpooled;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;

@Slf4j
@Component
@RequiredArgsConstructor
public class SipUdpHandler extends SimpleChannelInboundHandler<DatagramPacket> {
    
    private final SipMessageProcessor messageProcessor;
    private final SipTransactionManager transactionManager;
    
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) {
        try {
            // 解析SIP消息
            String message = packet.content().toString(StandardCharsets.UTF_8);
            SipMessage sipMessage = SipMessageParser.parse(message);
            
            InetSocketAddress sender = packet.sender();
            log.info("Received UDP SIP message from {}:{}", sender.getAddress().getHostAddress(), sender.getPort());
            log.debug("SIP message content: {}", message);
            
            // 处理SIP消息
            messageProcessor.processMessage(sipMessage, sender);

            // 查找并通过UDP发送响应
            if (sipMessage instanceof SipRequest) {
                SipRequest request = (SipRequest) sipMessage;
                SipTransaction transaction = transactionManager.findTransactionByRequest(request);
                if (transaction != null) {
                    // 发送临时响应（如有）
                    SipResponse provisional = transaction.getProvisionalResponse();
                    if (provisional != null) {
                        provisional.synchronizeContentHeaders();
                        String raw = provisional.toRawMessage();
                        DatagramPacket respPacket = new DatagramPacket(
                                Unpooled.wrappedBuffer(raw.getBytes(StandardCharsets.UTF_8)),
                                sender
                        );
                        ctx.writeAndFlush(respPacket);
                        log.debug("Sent provisional SIP response over UDP: {}", provisional.toRawMessage());
                    }

                    // 发送最终响应（如有）
                    SipResponse finalResp = transaction.getFinalResponse();
                    if (finalResp != null) {
                        finalResp.synchronizeContentHeaders();
                        String raw = finalResp.toRawMessage();
                        DatagramPacket respPacket = new DatagramPacket(
                                Unpooled.wrappedBuffer(raw.getBytes(StandardCharsets.UTF_8)),
                                sender
                        );
                        ctx.writeAndFlush(respPacket);
                        log.debug("Sent final SIP response over UDP: {}", finalResp.toRawMessage());
                        // 事务结束后移除
                        transaction.terminate();
                        transactionManager.removeTransaction(transaction);
                    }
                }
            }
            
        } catch (Exception e) {
            log.error("Error processing UDP SIP message: {}", e.getMessage(), e);
        }
    }
    
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.error("UDP Channel exception: {}", cause.getMessage(), cause);
        ctx.close();
    }
}
